import React, { useState, useEffect, useRef, RefObject } from 'react'
import { Button, Form, Col, Row, Select, DatePicker, Input, Space, message, FormInstance } from 'antd'
import moment from 'moment'
import _ from 'lodash'
import Text from '@src/components/text'
import style from './index.module.less'
import { $get } from '@js/request'
import { awaitWrap } from '@js/tool'
import Dictionary, { DictionaryItem } from '@js/dictionary';

const { Item } = Form
const { Option } = Select

function formatDate (t: number) {
  if (typeof t !== 'number') {
    return t
  }
  return moment(t * 1000).format('YYYY-MM-DD')
}

// 获取邮单的送达时间
async function getSendDateRequest (emscode: string) {
  const res = await $get(`/api/commission/ems/getArriveDatetimeByEmscode/${emscode}`)
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

// 初始化邮单送达时间
async function initSendDate (formRef: RefObject<FormInstance>, emscode: string) {
  const hide = message.loading('加载中', 120)
  const [e, d] = await awaitWrap(getSendDateRequest(emscode))
  hide()
  if (e !== null) {
    return message.error(e.message)
  }
  const c = formRef.current
  if (typeof d === 'number' && c !== null) {
    c.setFieldsValue({ arrive_datetime: moment(d * 1000) })
  }
}

// 显示详情
function Detail ({ data }: { data: {[k: string]: any} }) {
  const formRef = useRef<FormInstance>(null)
  useEffect(() => {
    const d = _.cloneDeep(data)
    d.arrive_datetime = formatDate(d.arrive_datetime)
    d.remark = d.remark || '无'
    if (formRef.current) {
      formRef.current.setFieldsValue(d)
    }
  }, [data])
  return (
    <div className={style['foot-form']}>
      <Form name='service-status-footer' ref={formRef} labelCol={{ flex: '96px' }}>
        <Row>
          <Col span={12}>
            <Item name='status_ex' label='送达情况'>
              <Text />
            </Item>
          </Col>
          <Col span={12}>
            <Item name='arrive_datetime' label='送达时间'>
              <Text />
            </Item>
          </Col>
        </Row>
        <Item name='remark' label='备注'>
          <Text />
        </Item>
      </Form>
    </div>
  )
}

// 改变完成状态
function setStatusEx (v: string, statusList: DictionaryItem[], formRef: RefObject<FormInstance>) {
  const list = statusList || []
  for (let i = 0; i < list.length; i++) {
    if (list[i].title === v) {
      formRef.current?.setFieldsValue({
        status: list[i].value,
        status_ex: v
      })
      break
    }
  }
}

interface DetailProps {
  statusList: DictionaryItem[],
  data: {[k: string]: any},
  hide: () => void,
  onFinish: (v: {[k: string]: any}) => void
}

function FormDetail ({ statusList, data, hide, onFinish }: DetailProps) {
  const formRef = useRef(null)
  useEffect(() => {
    if (data.emscode) {
      initSendDate(formRef, data.emscode)
    }
  }, [data])
  return (
    <div className={style['foot-form']}>
      <Form name='service-status-footer' labelCol={{ flex: '96px' }} ref={formRef} onFinish={d => onFinish(d)}>
        <Item name='status' noStyle><span /></Item>
        <Row>
          <Col span={12}>
            <Item name='status_ex' label='送达情况' rules={[{ required: true, message: '请选择送达情况' }]}>
              <Select placeholder='送达情况不能为空' onChange={v => setStatusEx(v, statusList, formRef)}>
                {statusList.map(li => <Option key={li.title} value={li.title}>{li.title}</Option>)}
              </Select>
            </Item>
          </Col>
          <Col span={12}>
            <Item name='arrive_datetime' label='送达时间' rules={[{ required: true, message: '请选择送达时间' }]}>
              <DatePicker placeholder='送达时间不能为空' className={style.full} />
            </Item>
          </Col>
        </Row>
        <Item name='remark' label='备注'>
          <Input placeholder='请输入备注' />
        </Item>
        <div className={style['foot-btns']}>
          <Space>
            <Button onClick={hide}>取消</Button>
            <Button type='primary' htmlType='submit'>确定</Button>
          </Space>
        </div>
      </Form>
    </div>
  )
}

interface Props {
  readOnly: boolean
  data: {[k: string]: any}
  hide: () => void
  finishStatus: (v: {[k: string]: any}) => void
}

function Main ({ readOnly, data, hide, finishStatus }: Props) {
  const [statusList, setStatusList] = useState<DictionaryItem[]>([])
  const [visible, setVisible] = useState(false)
  const [modifiable, setModifiable] = useState(false)
  useEffect(() => {
    const d = new Dictionary()
    d.init('送达完成情况')
      .then(() => {
        setStatusList(d.getList('送达完成情况'))
      })
      .catch(e => console.error(e))
  }, [])
  useEffect(() => {
    if (readOnly) {
      setModifiable(false)
    } else {
      setModifiable(statusList.map(li => li.title).indexOf(data.status_ex) === -1)
    }
  }, [data, readOnly, statusList])
  if (modifiable && !visible) {
    return <Button type='primary' onClick={() => setVisible(true)}>录入送达情况</Button>
  }
  if (modifiable && visible) {
    return <FormDetail data={data} statusList={statusList} hide={hide} onFinish={d => finishStatus(d)} />
  }
  if (!modifiable && data) {
    return <Detail data={data} />
  }
  return <span />
}

export default Main
